import { MongoGCPError } from "mongodb";
import { mongo } from "../mogoConfig";

const items = [{ item: "sunblock", qty: 3 },
{ item: "beach chair", qty: 1 }]


mongo.withSession(async session => session.withTransaction(async session => {
    const inventory = mongo.db("my_test").collection("inventory")
    const order = mongo.db("my_test").collection("orders")
    let total = 0

    for (const item of items) {
        const inStock = await inventory.findOneAndUpdate(
            {
                item: item.item,
                qty: { $gte: item.qty }
            },
            {
                $inc: {
                    qty: -item.qty
                }
            },
            { session }
        )

        console.log("inStock的值:", inStock)

        if (inStock === null) {
            await session.abortTransaction()
            return "Item not found or insufficient quantity."
        }

        total += item.qty * inStock.price
    }

    await order.insertOne({
        date: new Date(),
        items,
        total
    }, { session })

    return "Order successfully completed and recorded!"

}))
    .then((result) => {
        console.log(result)
    })
    .finally(() => {
        mongo.close()
    })